const BookModule = require("../../database/book");
const BorrowModule = require("../../database/borrow");
const UserModule = require("../../database/user");
const LeaveMessageMoudle = require("../database/leave_message");
const PublicInfoModule = require("../database/public_Info");
const { reduceBookNum, bookNumber } = require("../../wrapperFunction/index");
const { queryHistory } = require("./common");

// 查询图书
const query = async function (req, res, next) {
  try {
    const queryParam = req.query;
    console.log("查询参数为", queryParam);
    // result 目前是由模型对象的实例组成的数组
    let result = await BookModule.findAll({
      where: {
        book_name: req.query.book_name,
      },
    });
    // 转成josn数据返回至客户端
    result = result.map((item) => {
      return item.toJSON();
    });
    // console.log('result', result);
    res.status(200).json({
      msg: "查询数据成功",
      info: result,
    });
  } catch (error) {
    next({ msg: "controller-查询数据库中数据出错", error });
  }
};

// 借阅图书
const borrow = async function (req, res, next) {
  // 获取当前图书的数量
  let temp = await bookNumber(req.body.book_id);
  if (!temp) {
    // 图书数量不足，则不触发借阅操作
    // 书本数量为 0
    res.status(400).json({
      errors: [
        {
          msg: "当前图书库存不足",
        },
      ],
    });
  } else {
    // 图书数量充足，则触发借阅操作
    // 1. 获取传过来的数据
    let data = req.body;
    console.log("req.body", req.body);
    console.log("传过来的数据data：", data);
    data = data ? data : null;

    // 2. 把数据存入数据库
    try {
      const result = await BorrowModule.create(data);
      // 把图书的数量 -1
      reduceBookNum(req.body.book_id, next);

      res.status(201).json({
        msg: "借阅成功",
        result,
      });
    } catch (error) {
      next({
        msg: "图书借阅接口出错",
        error,
      });
    }
  }
};

// 借阅记录查询-用户接口
const queryBorrow = async function (req, res, next) {
  try {
    // 查询借阅记录
    queryHistory(req, res);
  } catch (error) {
    console.log("查询借阅记录接口调用失败", error);
    next({ msg: "借阅记录接口调用失败" }, error);
  }
};

// 留言
const infoFeedback = async function (req, res, next) {
  console.log(req.body);
  try {
    const data = await LeaveMessageMoudle.create(req.body);
    res.status(201).json({
      msg: "提交数据成功",
      info: data,
    });
  } catch (error) {
    console.log("添加失败", error);
    next({ msg: "添加失败", error });
  }
};

// 更改用户信息
const changeUserInfo = async function (req, res, next) {
  try {
    console.log(req.body);
    console.log(req.body.id);
    // 获取要改哪个用户的信息
    const data = await UserModule.findOne({
      where: {
        id: req.body.id,
      },
    });

    // 遍历传过来的对象，基于传过来的对象对数据库进行更改(对data的更改目前还是本地更改)
    Object.keys(req.body).forEach((key) => {
      console.log(key, "---", req.body[key]);
      data[key] = req.body[key];
    });
    // 把对data的本地更改提交到数据库
    const result = await data.save();

    res.status(201).json({
      msg: "修改成功",
      info: result,
    });
  } catch (error) {
    console.log("用户信息更改出错", error);
    next({ msg: "用户信息更改出错", error });
  }
};

// 获取公告信息
const getPublicInfo = async function (req, res, next) {
  try {
    const data = await PublicInfoModule.findOne({
      order: [["id", "DESC"]],
    });
    console.log("data", data);
    res.status(200).json({
      msg: "数据获取成功",
      info: data,
    });
  } catch (error) {
    console.log("获取公告信息出错", error);
    next({ msg: "获取公告信息出错", error });
  }
};

module.exports = {
  query,
  borrow,
  queryBorrow,
  infoFeedback,
  changeUserInfo,
  getPublicInfo,
};
